package Classes
{
	import UIUtils.uif_util;
	
	public class pi_packTmpl {
		private static const NOCHECKKEYS: Array = ['id', 'preview', 'order', 'pos'];
		private static const REMOVEKEYS: Array = ['order'];
		
		public function pi_packTmpl() {
		}

		public static function packTmplList(list: Array): Array {
			var top: Object;
			var next: Object;
			var inc: int = 0;
			var result: Array = new Array();
			for (var i: int=0; i<list.length; i++) {
				var tmpl: Object = list[i];
				for (var n:String in REMOVEKEYS) delete(tmpl[n]);
				if (!cmpObj(top, tmpl)) {
					if (top) {
						if ((top.id != next.id) && (inc == next.id - top.id)) {
							if (top.id is Array)
								top.id = [top.id[0], next.id]
							else top.id = [top.id, next.id]
						}
						result.push(top);
						inc = 0;
					} else inc++;
					top = tmpl;
					if (i == list.length - 1) 
						result.push(tmpl);
				} 
				next = tmpl;
			}
			return result;
		}
		
		public static function cmpObj(obj1: Object, obj2: Object): Boolean {
			if (!obj1 || !obj2) return false;
			
			if (uif_util.snb(obj1) && uif_util.snb(obj2)) 
				return (obj1 == obj2);
			else {
				function propList(obj: Object, toArr: Array=null): Array {
					var res: Array;
					if (!toArr) res = new Array();
					else res = toArr;
					for (var i: String in obj) 
						if ((!toArr || (res.indexOf(i) == -1)) && (NOCHECKKEYS.indexOf(i) == -1)) res.push(i);
					return res;
				}
			
				var props: Array = propList(obj2, propList(obj1));
				return !props.some(function(prop: String, index: int, arr: Array): Boolean {
					if (obj1.hasOwnProperty(prop) && obj2.hasOwnProperty(prop))
						return !cmpObj(obj1[prop], obj2[prop]);
					else return true;
				});
			}
		}
	}
}